package com.atguign.gulimall.ware.service.impl;

import com.atguign.gulimall.ware.dao.PurchaseDetailDao;
import com.atguign.gulimall.ware.dao.WareSkuDao;
import com.atguign.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguign.gulimall.ware.service.PurchaseDetailService;
import com.atguign.gulimall.ware.service.WareSkuService;
import com.atguign.gulimall.ware.vo.MorgeVo;
import com.atguign.gulimall.ware.vo.PurchaseDoneVo;
import com.atguign.gulimall.ware.vo.PurchaseItemDoneVo;
import com.atguigu.common.constant.WareConstant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguign.gulimall.ware.dao.PurchaseDao;
import com.atguign.gulimall.ware.entity.PurchaseEntity;
import com.atguign.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailDao purchaseDetailDao;
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), new QueryWrapper<PurchaseEntity>());

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> purchaseEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        purchaseEntityLambdaQueryWrapper.eq(PurchaseEntity::getStatus, 0).or().eq(PurchaseEntity::getStatus, 1);
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), purchaseEntityLambdaQueryWrapper);
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MorgeVo morgeVo) {
        Long purchaseId = morgeVo.getPurchaseId();
        Date date = new Date();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(date);
            purchaseEntity.setUpdateTime(date);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            LambdaUpdateWrapper<PurchaseEntity> purchaseEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            purchaseEntityLambdaUpdateWrapper.set(PurchaseEntity::getUpdateTime, date)
                    .eq(PurchaseEntity::getId, purchaseId)
                    .and(w -> {
                        w.eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATE.getCode());
                        w.or().eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
                    });
            int update = baseMapper.update(purchaseEntityLambdaUpdateWrapper);
            if (update == 0) throw new RuntimeException("已经领取");
        }
        LambdaUpdateWrapper<PurchaseDetailEntity> wrapperPurchaseDetailEntity = new LambdaUpdateWrapper<>();

        wrapperPurchaseDetailEntity.in(PurchaseDetailEntity::getId, morgeVo.getItems()).and(w -> {
            w.eq(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.CREATE.getCode());
            w.or().eq(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
        }).set(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()).set(PurchaseDetailEntity::getPurchaseId, purchaseId);
        purchaseDetailDao.update(wrapperPurchaseDetailEntity);
    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        Date date = new Date();
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PurchaseEntity::getId, ids).eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        List<PurchaseEntity> purchaseEntities = baseMapper.selectList(wrapper);
        if (purchaseEntities == null || purchaseEntities.isEmpty()) return;
        List<Long> collect = purchaseEntities.stream().map(item -> {
            item.setUpdateTime(date);
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item.getId();
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);
        LambdaUpdateWrapper<PurchaseDetailEntity> purchaseDetailEntityWrapper = new LambdaUpdateWrapper<>();
        purchaseDetailEntityWrapper.in(PurchaseDetailEntity::getPurchaseId, collect)
                .set(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        purchaseDetailDao.update(purchaseDetailEntityWrapper);
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        Long l = purchaseDetailDao.selectCount(new LambdaQueryWrapper<PurchaseDetailEntity>()
                .eq(PurchaseDetailEntity::getPurchaseId, id)
                .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.FINISH.getCode())
                .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.CREATE.getCode())
        );
        if (l == 0) return;
        ArrayList<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        int allupdate = 0;
        for (PurchaseItemDoneVo item : items) {
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                allupdate += purchaseDetailDao.update(new LambdaUpdateWrapper<PurchaseDetailEntity>()
                        .eq(PurchaseDetailEntity::getPurchaseId, id)
                        .eq(PurchaseDetailEntity::getId, item.getItemId())
                        .eq(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.BUYING.getCode())
                        .set(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode())
                );
            } else if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()) {
                int update = purchaseDetailDao.update(new LambdaUpdateWrapper<PurchaseDetailEntity>()
                        .eq(PurchaseDetailEntity::getPurchaseId, id)
                        .eq(PurchaseDetailEntity::getId, item.getItemId())
                        .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.FINISH.getCode())
                        .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                        .ne(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.CREATE.getCode())
                        .set(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.FINISH.getCode())
                );
                allupdate += update;
                l -= update;
                //采购成功
                if (update != 0) {
                    PurchaseDetailEntity purchaseDetail = purchaseDetailDao.selectById(item.getItemId());
                    wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());
                }
            }

        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        if (l == 0) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else if (allupdate != 0) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        baseMapper.updateById(purchaseEntity);
    }

}